package com.bzkj.common.utils.http;
/**
 * @projectName: bzkj-wms
 * @package: com.bzkj.common.utils.http
 * @className: NccHttpUtils
 * @description: Ncc接口Http请求工具类
 * @author: C1309
 * @createDate: 2024年11月04日
 * @version: v1.0
 */

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bzkj.common.domain.NccApiResponse;
import com.bzkj.common.domain.NccRequestDTO;
import com.bzkj.common.mapper.SelectInfoMapper;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.date.WmsDateUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class NccHttpUtils {

    @Value("${ncc.sourceSystem}")
    private String sourceSystem;

    @Value("${ncc.targetSystem}")
    private String targetSystem;

    @Value("${ncc.serviceName}")
    private String serviceName;

    @Value("${ncc.contentType}")
    private String contentType;

    @Value("${ncc.baseUrl}")
    private String baseUrl;

    @Value("${pk_org.code}")
    private String PK_ORG;

    @Resource
    private SelectInfoMapper selectInfoMapper;

    private static final CloseableHttpClient HTTP_CLIENT;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    // 初始化 HTTP 客户端，使用连接池确保线程安全
    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 最大连接数
        connectionManager.setMaxTotal(100);
        // 每个路由的最大连接数
        connectionManager.setDefaultMaxPerRoute(20);
        HTTP_CLIENT = HttpClients.custom().setConnectionManager(connectionManager).build();
    }


    /**
     * 发送 POST 请求
     *
     * @param path 请求路径
     * @param requestBody 请求体，JSON 字符串
     * @return 响应内容，解析为 Map
     * @throws IOException IO 异常
     */
    public NccApiResponse post(String path, String requestBody) throws IOException {
        // 创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(baseUrl);
            httpPost.setHeader("SourceSystem", sourceSystem);
            httpPost.setHeader("TargetSystem", targetSystem);
            if (path.equals("/nccloud/api/bqreport/report/query") && baseUrl.equals("http://192.168.132.88:8000/v1.0/ncc/json/goThroughApi")) {
                httpPost.setHeader("ServiceName", "S011010001B");
            } else {
                httpPost.setHeader("ServiceName", serviceName);
            }
            httpPost.setHeader("Content-Type", contentType);
            httpPost.setHeader("path", path);

            // 设置请求体
            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                // 解析响应并封装为 ApiResponse 对象
                NccApiResponse apiResponse = OBJECT_MAPPER.readValue(responseBody, NccApiResponse.class);
                // 将返回的 data 转换为 JSONArray
                if (apiResponse.isSuccess() && apiResponse.getData() != null) {
                    Object data = apiResponse.getData();
                    if (data instanceof String) {
                        String dataStr = (String) data;
                        JSONArray jsonArray = new JSONArray();
                        if (dataStr.startsWith("[")) {
                            jsonArray = JSONArray.parseArray(dataStr);
                        } else {
                            jsonArray.add(JSONObject.parseObject(dataStr));
                        }
                        apiResponse.setData(jsonArray);
                    }
                }
                return apiResponse;
            }
        }
    }

    /**
     * 处理仓库权限
     */
    public void setWarehouseId(NccRequestDTO requestDTO, Set<String> warehouseIds) {
        if (requestDTO.getWarehouseid() == null || warehouseIds.isEmpty()) {
            Set<String> userWarehouses = SecurityUtils.getLoginUser().getWarehouses();
            Set<String> resultWarehouses = userWarehouses.contains("*")
                    ? new HashSet<>(warehouseIds)
                    : userWarehouses.stream()
                    .filter(warehouseIds::contains)
                    .collect(Collectors.toSet());

            requestDTO.setWarehouseid(resultWarehouses);
        } else {
            Set<String> warehouseid = requestDTO.getWarehouseid();
            String cwarehouseid = "";
            for (String s : warehouseid) {
                cwarehouseid = selectInfoMapper.getWarehouseId(s);
            }

            HashSet<String> hashSet = new HashSet<>();
            if (cwarehouseid != null) {
                hashSet.add(cwarehouseid);
            }
            requestDTO.setWarehouseid(hashSet);
        }
    }

    /**
     * 获取单据日期，默认返回最近30天的范围
     */
    public String getBillDate(String billDate) {
        return billDate != null ? billDate : WmsDateUtils.setDefaultDateRange(-30);
    }

    /***
     * 单据确认查询条件构建
     */
    public String getConfirmQuery(String billDate, String billCode) {
        Map<String, Object> requestMap = new HashMap<>(3);
        requestMap.put("dbilldate", billDate);
        requestMap.put("vbillcode", Collections.singletonList(billCode));
        requestMap.put("pk_org", PK_ORG);
        return JSONObject.toJSONString(requestMap);
    }

    /**
     * 单据确认后返回状态给NCC（除销售出库单外）
     * 其他单据：vdef18
     *
     * @param cgeneralhid 表头主键
     * @param path        请求路径
     * @param orderType   单据类型
     * @return NccApiResponse 请求结果
     */
    public NccApiResponse postNoSaleConfirm(String path, String cgeneralhid, String orderType, String contentType) throws IOException {
        HashMap<Object, Object> requestMap = new HashMap<>(2);
        requestMap.put("cgeneralhid", cgeneralhid);
        requestMap.put("vdef18", contentType);

        HashMap<Object, Object> requestHashMap = new HashMap<>(2);
        requestHashMap.put(orderType, requestMap);
        if ("ic_finprodin_h".equals(orderType)) {
            requestHashMap.put("ic_finprodin_b", Collections.emptyList());
        }
        return post(path, JSONObject.toJSONString(requestHashMap));
    }

    /**
     * 单据确认后返回状态给NCC（销售出库单）
     * 销售出库单：vdef38
     *
     * @param cgeneralhid 表头主键
     * @param path        请求路径
     * @return NccApiResponse 请求结果
     */
    public NccApiResponse postSaleConfirm(String path, String cgeneralhid, String contentType) throws IOException {
        HashMap<Object, Object> requestMap = new HashMap<>(2);
        requestMap.put("cgeneralhid", cgeneralhid);
        requestMap.put("vdef38", contentType);

        HashMap<Object, Object> requsetHashMap = new HashMap<>(1);
        requsetHashMap.put("ic_saleout_h", requestMap);
        return post(path, JSONObject.toJSONString(requsetHashMap));
    }

    /**
     * 单据确认后返回状态给NCC（销售出库单）
     * 销售出库单：vdef38
     *
     * @param cgeneralhid 表头主键
     * @param path        请求路径
     * @return NccApiResponse 请求结果
     */
    public NccApiResponse postMoveConfirm(String path, String cgeneralhid, String contentType) throws IOException {
        HashMap<Object, Object> requestMap = new HashMap<>(2);
        requestMap.put("cspecialhid", cgeneralhid);
        requestMap.put("vdef18", contentType);

        HashMap<Object, Object> requsetHashMap = new HashMap<>(1);
        requsetHashMap.put("ic_whstrans_h", requestMap);
        return post(path, JSONObject.toJSONString(requsetHashMap));
    }

    /**
     * 发送 POST 请求
     *
     * @param path        请求路径
     * @param requestBody 请求体，JSON 字符串
     * @return 响应内容，解析为 Map
     * @throws IOException IO 异常
     */
//    public NccApiResponse post(String path, String requestBody) throws IOException {
//        // 创建 HttpClient
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            HttpPost httpPost = new HttpPost("http://ze46438a.natappfree.cc/ncc?" + "url=" + path);
//            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
//            httpPost.setEntity(entity);
//            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
//                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//                // 解析响应并封装为 ApiResponse 对象
//                NccApiResponse apiResponse = OBJECT_MAPPER.readValue(responseBody, NccApiResponse.class);
//                // 将返回的 data 转换为 JSONArray
//                if (apiResponse.isSuccess() && apiResponse.getData() != null) {
//                    Object data = apiResponse.getData();
//                    if (data instanceof String) {
//                        String dataStr = (String) data;
//                        JSONArray jsonArray = new JSONArray();
//                        if (dataStr.startsWith("[")) {
//                            jsonArray = JSONArray.parseArray(dataStr);
//                        } else {
//                            jsonArray.add(JSONObject.parseObject(dataStr));
//                        }
//                        apiResponse.setData(jsonArray);
//                    }
//                }
//                return apiResponse;
//            }
//        }
//    }
}
